#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
视力记录数据模型 - 完整版本v3.2
支持基线判定、测量次序、年龄计算等完整功能
修复：添加缺失的散瞳视力字段，完善to_dict()方法
"""

from sqlalchemy import Column, Integer, String, Float, Date, Time, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from backend.infrastructure.database import db

class VisionRecord(db.Model):
    """
    视力记录模型 - 按技术文档B标准设计v3.2
    支持基线判定、测量次序、基线对比等完整功能
    修复：添加缺失的散瞳视力字段
    """
    __tablename__ = 'vision_records'
    
    # ✅基础字段（v3.2）
    id = Column(Integer, primary_key=True, autoincrement=True, comment='记录ID')
    student_id = Column(Integer, ForeignKey('students.id', ondelete='CASCADE'), 
                       nullable=False, index=True, comment='学生ID')
    
    # ✅测量基础信息（v3.2）
    measure_date = Column(Date, nullable=False, index=True, comment='测量日期')
    measure_time = Column(Time, nullable=True, comment='测量时间')
    measure_location = Column(String(100), nullable=True, comment='检查地点（机构）')
    measure_type = Column(String(20), nullable=False, default='常规检查', 
                         comment='测量类型：基线数据/随访数据/常规检查')
    measurer = Column(String(50), nullable=True, comment='测量员')
    
    # ✅基线判定和测量次序字段（v3.2）
    is_baseline = Column(Boolean, nullable=False, default=False, 
                        index=True, comment='是否为基线记录')
    measurement_sequence = Column(Integer, nullable=True, 
                                comment='测量次序（按日期排序的序号）')
    age_at_measure = Column(Integer, nullable=True, 
                          comment='测量时年龄（精确计算）')
    
    # ✅数据管理字段（v3.2）
    data_year = Column(String(4), nullable=False, index=True, comment='数据年份')
    created_at = Column(DateTime, nullable=False, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, nullable=False, default=datetime.now, 
                       onupdate=datetime.now, comment='更新时间')
    
    # ✅裸眼视力（v3.2）
    left_eye_naked = Column(Float(precision=2), nullable=True, comment='左眼裸眼视力')
    right_eye_naked = Column(Float(precision=2), nullable=True, comment='右眼裸眼视力')
    
    # ✅矫正视力（v3.2）
    left_eye_corrected = Column(Float(precision=2), nullable=True, comment='左眼矫正视力')
    right_eye_corrected = Column(Float(precision=2), nullable=True, comment='右眼矫正视力')
    
    # ✅屈光度数据（v3.2）
    left_sphere = Column(Float(precision=2), nullable=True, comment='左眼球镜度数')
    right_sphere = Column(Float(precision=2), nullable=True, comment='右眼球镜度数')
    left_cylinder = Column(Float(precision=2), nullable=True, comment='左眼柱镜度数')
    right_cylinder = Column(Float(precision=2), nullable=True, comment='右眼柱镜度数')
    left_axis = Column(Float(precision=1), nullable=True, comment='左眼轴位')
    right_axis = Column(Float(precision=1), nullable=True, comment='右眼轴位')
    
    # ✅散瞳屈光数据（v3.2 - 修复：添加缺失的散瞳视力字段）
    left_dilated_sphere = Column(Float(precision=2), nullable=True, comment='左眼散瞳球镜')
    right_dilated_sphere = Column(Float(precision=2), nullable=True, comment='右眼散瞳球镜')
    left_dilated_cylinder = Column(Float(precision=2), nullable=True, comment='左眼散瞳柱镜')
    right_dilated_cylinder = Column(Float(precision=2), nullable=True, comment='右眼散瞳柱镜')
    left_dilated_axis = Column(Float(precision=1), nullable=True, comment='左眼散瞳轴位')
    right_dilated_axis = Column(Float(precision=1), nullable=True, comment='右眼散瞳轴位')
    left_dilated_vision = Column(Float(precision=2), nullable=True, comment='左眼散瞳视力')
    right_dilated_vision = Column(Float(precision=2), nullable=True, comment='右眼散瞳视力')
    
    # ✅眼轴和角膜数据（v3.2）
    left_axial_length = Column(Float(precision=2), nullable=True, comment='左眼眼轴长度(mm)')
    right_axial_length = Column(Float(precision=2), nullable=True, comment='右眼眼轴长度(mm)')
    left_keratometry_K1 = Column(Float(precision=2), nullable=True, comment='左眼角膜曲率K1')
    right_keratometry_K1 = Column(Float(precision=2), nullable=True, comment='右眼角膜曲率K1')
    left_keratometry_K2 = Column(Float(precision=2), nullable=True, comment='左眼角膜曲率K2')
    right_keratometry_K2 = Column(Float(precision=2), nullable=True, comment='右眼角膜曲率K2')
    left_anterior_depth = Column(Float(precision=2), nullable=True, comment='左眼前房深度')
    right_anterior_depth = Column(Float(precision=2), nullable=True, comment='右眼前房深度')
    
    # ✅自动计算字段（v3.2）
    left_se = Column(Float(precision=2), nullable=True, comment='左眼等效球镜度（自动计算）')
    right_se = Column(Float(precision=2), nullable=True, comment='右眼等效球镜度（自动计算）')
    left_dilated_se = Column(Float(precision=2), nullable=True, comment='左眼散瞳等效球镜度（自动计算）')
    right_dilated_se = Column(Float(precision=2), nullable=True, comment='右眼散瞳等效球镜度（自动计算）')
    
    # ✅视力等级分级字段（v3.2）
    left_vision_level = Column(String(20), nullable=True, comment='左眼视力等级（自动计算）')
    right_vision_level = Column(String(20), nullable=True, comment='右眼视力等级（自动计算）')
    comprehensive_vision_level = Column(String(20), nullable=True, comment='综合视力等级（自动计算）')
    vision_level = Column(String(20), nullable=True, comment='视力水平分级（自动计算）')
    myopia_degree = Column(String(20), nullable=True, comment='近视程度分级（自动计算）')
    
    # ✅基线对比变化值字段（v3.2）
    baseline_left_naked_change = Column(Float(precision=3), nullable=True, 
                                      comment='左眼裸眼视力相对基线变化')
    baseline_right_naked_change = Column(Float(precision=3), nullable=True, 
                                       comment='右眼裸眼视力相对基线变化')
    baseline_left_sphere_change = Column(Float(precision=3), nullable=True, 
                                       comment='左眼球镜相对基线变化')
    baseline_right_sphere_change = Column(Float(precision=3), nullable=True, 
                                        comment='右眼球镜相对基线变化')
    baseline_left_se_change = Column(Float(precision=3), nullable=True, 
                                   comment='左眼SE相对基线变化')
    baseline_right_se_change = Column(Float(precision=3), nullable=True, 
                                    comment='右眼SE相对基线变化')
    baseline_left_cylinder_change = Column(Float(precision=3), nullable=True, 
                                         comment='左眼柱镜相对基线变化')
    baseline_right_cylinder_change = Column(Float(precision=3), nullable=True, 
                                          comment='右眼柱镜相对基线变化')
    baseline_left_axis_change = Column(Float(precision=2), nullable=True, 
                                     comment='左眼轴位相对基线变化')
    baseline_right_axis_change = Column(Float(precision=2), nullable=True, 
                                      comment='右眼轴位相对基线变化')
    
    # ✅基线对比效果评估字段（v3.2）
    baseline_left_vision_effect = Column(String(20), nullable=True, comment='左眼视力干预效果')
    baseline_right_vision_effect = Column(String(20), nullable=True, comment='右眼视力干预效果')
    baseline_left_se_effect = Column(String(20), nullable=True, comment='左眼SE干预效果')
    baseline_right_se_effect = Column(String(20), nullable=True, comment='右眼SE干预效果')
    baseline_left_sphere_effect = Column(String(20), nullable=True, comment='左眼球镜干预效果')
    baseline_right_sphere_effect = Column(String(20), nullable=True, comment='右眼球镜干预效果')
    baseline_left_cylinder_effect = Column(String(20), nullable=True, comment='左眼柱镜干预效果')
    baseline_right_cylinder_effect = Column(String(20), nullable=True, comment='右眼柱镜干预效果')
    baseline_left_axis_effect = Column(String(20), nullable=True, comment='左眼轴位干预效果')
    baseline_right_axis_effect = Column(String(20), nullable=True, comment='右眼轴位干预效果')
    
    # ✅其他信息（v3.2）
    eye_fatigue = Column(String(100), nullable=True, comment='眼疲劳症状')
    other_info = Column(Text, nullable=True, comment='其他检查信息')
    equipment_model = Column(String(100), nullable=True, comment='检查设备型号')
    remarks = Column(Text, nullable=True, comment='备注信息')
    
    # ✅关系定义（v3.2）
    student = relationship("Student", back_populates="vision_records")
    
    # ✅索引和约束（v3.2）
    __table_args__ = (
        # 确保每个学生只有一条基线记录
        db.Index('ix_student_baseline', 'student_id', 'is_baseline'),
        # 测量日期索引
        db.Index('ix_measure_date_year', 'measure_date', 'data_year'),
        # 复合查询索引
        db.Index('ix_student_date_type', 'student_id', 'measure_date', 'measure_type'),
        # 检查地点索引
        db.Index('ix_measure_location', 'measure_location'),
        {'comment': '视力记录表v3.2 - 支持基线判定、测量次序管理和检查地点记录'}
    )
    
    def __repr__(self):
        return f'<VisionRecord {self.id}: Student{self.student_id} - {self.measure_date} ({self.measure_type}) @ {self.measure_location or "未知地点"}>'
    
    def to_dict(self):
        """转换为字典格式 - v3.2完整版本（包含所有字段）"""
        return {
            'id': self.id,
            'student_id': self.student_id,
            'measure_date': self.measure_date.isoformat() if self.measure_date is not None else None,
            'measure_time': self.measure_time.isoformat() if self.measure_time is not None else None,
            'measure_location': self.measure_location,
            'measure_type': self.measure_type,
            'measurer': self.measurer,
            'is_baseline': self.is_baseline,
            'measurement_sequence': self.measurement_sequence,
            'age_at_measure': self.age_at_measure,
            'data_year': self.data_year,
            'left_eye_naked': self.left_eye_naked,
            'right_eye_naked': self.right_eye_naked,
            'left_eye_corrected': self.left_eye_corrected,
            'right_eye_corrected': self.right_eye_corrected,
            'left_sphere': self.left_sphere,
            'right_sphere': self.right_sphere,
            'left_cylinder': self.left_cylinder,
            'right_cylinder': self.right_cylinder,
            'left_axis': self.left_axis,
            'right_axis': self.right_axis,
            # ✅修复：添加所有散瞳字段
            'left_dilated_sphere': self.left_dilated_sphere,
            'right_dilated_sphere': self.right_dilated_sphere,
            'left_dilated_cylinder': self.left_dilated_cylinder,
            'right_dilated_cylinder': self.right_dilated_cylinder,
            'left_dilated_axis': self.left_dilated_axis,
            'right_dilated_axis': self.right_dilated_axis,
            'left_dilated_vision': self.left_dilated_vision,
            'right_dilated_vision': self.right_dilated_vision,
            # ✅修复：添加所有生物测量字段
            'left_keratometry_K1': self.left_keratometry_K1,
            'right_keratometry_K1': self.right_keratometry_K1,
            'left_keratometry_K2': self.left_keratometry_K2,
            'right_keratometry_K2': self.right_keratometry_K2,
            'left_axial_length': self.left_axial_length,
            'right_axial_length': self.right_axial_length,
            'left_anterior_depth': self.left_anterior_depth,
            'right_anterior_depth': self.right_anterior_depth,
            # ✅修复：添加所有计算字段
            'left_se': self.left_se,
            'right_se': self.right_se,
            'left_dilated_se': self.left_dilated_se,
            'right_dilated_se': self.right_dilated_se,
            'left_vision_level': self.left_vision_level,
            'right_vision_level': self.right_vision_level,
            'comprehensive_vision_level': self.comprehensive_vision_level,
            'vision_level': self.vision_level,
            'myopia_degree': self.myopia_degree,
            # ✅修复：添加所有基线对比变化值字段
            'baseline_left_naked_change': self.baseline_left_naked_change,
            'baseline_right_naked_change': self.baseline_right_naked_change,
            'baseline_left_sphere_change': self.baseline_left_sphere_change,
            'baseline_right_sphere_change': self.baseline_right_sphere_change,
            'baseline_left_se_change': self.baseline_left_se_change,
            'baseline_right_se_change': self.baseline_right_se_change,
            'baseline_left_cylinder_change': self.baseline_left_cylinder_change,
            'baseline_right_cylinder_change': self.baseline_right_cylinder_change,
            'baseline_left_axis_change': self.baseline_left_axis_change,
            'baseline_right_axis_change': self.baseline_right_axis_change,
            # ✅修复：添加所有基线对比效果评估字段
            'baseline_left_vision_effect': self.baseline_left_vision_effect,
            'baseline_right_vision_effect': self.baseline_right_vision_effect,
            'baseline_left_se_effect': self.baseline_left_se_effect,
            'baseline_right_se_effect': self.baseline_right_se_effect,
            'baseline_left_sphere_effect': self.baseline_left_sphere_effect,
            'baseline_right_sphere_effect': self.baseline_right_sphere_effect,
            'baseline_left_cylinder_effect': self.baseline_left_cylinder_effect,
            'baseline_right_cylinder_effect': self.baseline_right_cylinder_effect,
            'baseline_left_axis_effect': self.baseline_left_axis_effect,
            'baseline_right_axis_effect': self.baseline_right_axis_effect,
            # ✅修复：添加所有其他信息字段
            'eye_fatigue': self.eye_fatigue,
            'other_info': self.other_info,
            'equipment_model': self.equipment_model,
            'remarks': self.remarks,
            'created_at': self.created_at.isoformat() if self.created_at is not None else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at is not None else None
        }
